import {reqgetCode,reqRegisterUser,reqLogin,reqgetUserInfo,reqLoginout} from '@/api'
//登录与注册的模块
const state = {
    code:'',
    token:localStorage.getItem('token'),
    UserInfo:{},
}
const mutations = {
    GETCODE(state,code){
        state.code = code
    },
    USERLOGIN(state,token){
        state.token = token
        },
    GETUSERINFO(state, Info) {
        state.UserInfo = Info
    },
    LOGINOUT(state){
		state.token = localStorage.removeItem('token')
		state.UserInfo = {}
	},
}
const actions = {
    //获取验证码
    async getCode({ commit }, phone) {
        //获取验证码的接口，把验证码返回，但是正常情况下后台把验证码发到用户手机上（省钱）
        let result = await reqgetCode(phone)
        if (result.code == 200) {
            commit('GETCODE', result.data)
            return 'ok'
        } else {
            return Promise.reject(new Error('faile'))
        }
    },
    //用户注册
    async registerUser({ commit }, data) {
        let result = await reqRegisterUser(data)
        if (result.code == 200) {
            return 'ok'
        } else {
            return Promise.reject(new Error(result.message))//返回错误信息
        }
    },
    //用户登录业务（token）
    async userLogin({ commit }, data) {
        let result = await reqLogin(data)
        if (result.code == 200) {
            commit('USERLOGIN', result.data.token)
            localStorage.setItem('token', result.data.token)//存储token 
            return 'ok'
        } else {
            return Promise.reject(new Error('登录失败'))
        }
    },
    //获取用户信息
    async getUserInfo({commit}){
		let result = await reqgetUserInfo()
		if(result.code == 200){
			commit("GETUSERINFO",result.data)
			return 'ok'
		}else{
			// return Promise.reject(new Error('获取信息失败'))
		}
	},
    //退出登录
    async LoginOut({commit}){
        let result =  await reqLoginout()
          if(result.code ==200){ 
          commit('LOGINOUT')
          return 'ok'
      }else{
          return Promise.reject(new Error(result.messge))
      }
      }

}
const getters = {}
export default{
    state,
    mutations,
    actions,
    getters
}